# @file
# 
# @copyright
#  INTEL CONFIDENTIAL
#  Copyright 2016 Intel Corporation.
#
#  The source code contained or described herein and all documents related to the
#  source code ("Material") are owned by Intel Corporation or its suppliers or
#  licensors. Title to the Material remains with Intel Corporation or its suppliers
#  and licensors. The Material may contain trade secrets and proprietary and
#  confidential information of Intel Corporation and its suppliers and licensors,
#  and is protected by worldwide copyright and trade secret laws and treaty
#  provisions. No part of the Material may be used, copied, reproduced, modified,
#  published, uploaded, posted, transmitted, distributed, or disclosed in any way
#  without Intel's prior express written permission.
#
#  No license under any patent, copyright, trade secret or other intellectual
#  property right is granted to or conferred upon you by disclosure or delivery
#  of the Materials, either expressly, by implication, inducement, estoppel or
#  otherwise. Any license under such intellectual property rights must be
#  express and approved by Intel in writing.
#
#  Unless otherwise agreed by Intel in writing, you may not remove or alter
#  this notice or any other notice embedded in Materials by Intel or
#  Intel's suppliers or licensors in any way.
#
#  This file contains a 'Sample Driver' and is licensed as such under the terms
#  of your license agreement with Intel or your vendor. This file may be modified
#  by the user, subject to the additional terms of the license agreement.
#
# @par Specification Reference:
#

PrepRelease=DEBUG
export SILENT_MODE=FALSE
CapsuleBuild=FALSE

#
# If NUMBER_OF_PROCESSORS environment variable is uninitialized
#
if [ ! $NUMBER_OF_PROCESSORS ]; then
  export NUMBER_OF_PROCESSORS=$(nproc)
fi

# VAR_BUILD_FLAGS contains user build flags, it is not modified by build scripts
export EXT_BUILD_FLAGS=$VAR_BUILD_FLAGS

function PrintUsage {
  echo "Client BIOS build script"
  echo
  echo "$0 [-f FLAG VALUE] [/f FLAG VALUE] [-r] [/r] [r] [s] [c] [rc]"
  echo
  echo "  r        Build in release mode. Default is debug"
  echo "  s        Build in silent mode."
  echo "  c        Build with CapsuleBuild=TRUE (Debug build). See note 1"
  echo "  rc       Build with CapsuleBuild=TRUE (Release build). See note 1"
  echo "  -f or /f Sets a build flag to the given value,"
  echo "           can be used as many times as desired.  See note 1"
  echo "  -r or /r Useful for faster rebuilds when no changes have been made to .inf files,"
  echo "           skips the generation of makefiles."
  echo
  echo "1) Re-running $0 without these arguments cannot be used for"
  echo "   incremental build. Hence, these inputs must be supplied every time"
  echo "   $0 is run.  For consistent build flags, set VAR_BUILD_FLAGS"
  echo "   prior to $0"
  echo
}

if [ -e "PlatformPkgExtConfig.dsc" ]; then
  chmod u+w PlatformPkgExtConfig.dsc
fi
#
# If EXT_CONFIG_CLEAR environment variable is uninitialized
#
if [ ! $EXT_CONFIG_CLEAR ]; then
  echo > PlatformPkgExtConfig.dsc
fi
#@todo: Add support for FSP build options (fspb, fspw) and pacm
numargs=$#
for ((i=1 ; i <= numargs ; i++)); do
  if [ "$1" = "r" ]; then
    PrepRelease=RELEASE
  elif [ "$1" = "rp" ]; then
    PrepRelease=RELEASE_PDB
  elif [ "$1" = "s" ]; then
    export SILENT_MODE=TRUE
  elif [ "$1" = "c" ]; then
    CapsuleBuild=TRUE
  elif [ "$1" = "rc" ]; then
    PrepRelease=RELEASE
    CapsuleBuild=TRUE
  elif [ "$1" = "perf" ]; then
    echo "gPlatformModuleTokenSpaceGuid.PcdPerformanceEnable|TRUE" >> PlatformPkgExtConfig.dsc
  elif [ "$1" = "embedded" ]; then
    echo "gPlatformModuleTokenSpaceGuid.PcdEmbeddedEnable|TRUE" >> PlatformPkgExtConfig.dsc
  elif [ "$1" = "help" ] ||  [ "$1" = "-h" ] || [ "$1" = "/?" ] || [ "$1" = "--help" ]; then
    PrintUsage
    exit 0
  elif [ "$1" = "/f" ] || [ "$1" = "-f" ]; then
    if [ -z "$2" ] || [ -z "$3" ]; then
      PrintUsage
      exit 1
    fi
    echo "%2|%3" >> PlatformPkgExtConfig.dsc
    shift
    shift
  elif [ "$1" = "/r" ] || [ "$1" = "-r" ]; then
    export EXT_BUILD_FLAGS="$EXT_BUILD_FLAGS -u"
  elif [ -n "$1" ]; then
    echo "Invalid input argument: $1"
    echo
    PrintUsage
    exit 1
  fi
  shift
done
echo "EXT_BUILD_FLAGS: $EXT_BUILD_FLAGS"
if [ -e Prep.log ]; then
	rm Prep.log
fi

echo "=============================================="
echo "Dumping PlatformPkgExtConfig.dsc"
cat PlatformPkgExtConfig.dsc
echo "=============================================="

#
# Define platform specific environment variables.
#
export PLATFORM_PACKAGE=KabylakePlatSamplePkg
export PLATFORM_SI_PACKAGE=KabylakeSiliconPkg
export CLIENT_COMMON_PACKAGE=ClientCommonPkg
export BP_COMMON_PACKAGE=BpCommonPkg

#
# Setup basic environment
#

# ROYAL_PARK_OVERRIDE: RoyalParkOverrideBegin - RPPO-KBL-0035
cd ..
if [ "$PrepRelease" = "RELEASE_PDB" ]; then
  cp -f $PLATFORM_PACKAGE/Override/BaseTools/Conf/tools_def_pdb.template Conf/tools_def.txt
else
  cp -f $PLATFORM_PACKAGE/Override/BaseTools/Conf/tools_def.template Conf/tools_def.txt
fi
cp -f $PLATFORM_PACKAGE/Override/BaseTools/Conf/build_rule.template Conf/build_rule.txt
# ROYAL_PARK_OVERRIDE: RoyalParkOverrideEnd
#if [ -e Conf/build_rule.txt ]; then
#  rm Conf/build_rule.txt
#fi
if [ -e Conf/BuildEnv.sh ]; then
  rm Conf/BuildEnv.sh
fi
source edksetup.sh
export PATH=$PATH:$WORKSPACE/$PLATFORM_PACKAGE/Tools/ToolScripts/SignFv

#
# Detect GCC Tool Chain Version
#
GCC_VERSION=$(gcc --version | grep ^gcc | sed 's/^.* //g' | sed 's/\.[0-9]*$//g')
if [ "$GCC_VERSION" = "4.5" ]; then
  export TOOL_CHAIN_TAG=GCC45
elif [ "$GCC_VERSION" = "4.6" ]; then
  export TOOL_CHAIN_TAG=GCC46
elif [ "$GCC_VERSION" = "4.7" ]; then
  export TOOL_CHAIN_TAG=GCC47
elif [ "$GCC_VERSION" = "4.8" ]; then
  export TOOL_CHAIN_TAG=GCC48
elif [ "$GCC_VERSION" = "4.9" ]; then
  export TOOL_CHAIN_TAG=GCC49
else
  echo "Unsupported GCC version!"
  exit 1
fi

#
# Set build TARGET
#
if [ "$PrepRelease" = "DEBUG" ]; then
  export TARGET=DEBUG
  export TARGET_SHORT=D
elif [ "$PrepRelease" = "RELEASE" ]; then
  export TARGET=RELEASE
  export TARGET_SHORT=R
elif [ "$PrepRelease" = "RELEASE_PDB" ]; then
  export TARGET=RELEASE
  export TARGET_SHORT=R
else
  echo
  echo "!!! ERROR !!! Incorrect TARGET option !!!"
  echo
  exit 1
fi
BUILD_DIR="Build/$PLATFORM_PACKAGE/$TARGET"
BUILD_DIR+="_$TOOL_CHAIN_TAG"
export BUILD_DIR
export BUILD_X64=$BUILD_DIR/X64
export BUILD_IA32=$BUILD_DIR/IA32
export BIOS_ID_FILE=$BUILD_DIR/BiosId.env

if [ "$CapsuleBuild" = "FALSE" ]; then
  export INTERNAL_BUILD=0

  #
  # Determine BIOS Build Type
  #
  # C - Code Coverage, R - RVP/Restricted, N - Non-Restricted, I - Internal, P - Performance, S - SV, E - SLE
  #

  export BUILD=X
  echo $EXT_BUILD_FLAGS | grep "PERFORMANCE_ENABLE=TRUE"
  if [ "$?" -eq 0 ]; then
    export BUILD=P
    cat "$WORKSPACE/$PLATFORM_PACKAGE/PlatformPkgConfig.dsc" | grep "gPlatformModuleTokenSpaceGuid.PcdPerformanceEnable|TRUE" > /dev/null
    if [ "$?" -ne 0 ]; then
      cat "$WORKSPACE/$PLATFORM_PACKAGE/PlatformPkgExtConfig.dsc" | grep "gPlatformModuleTokenSpaceGuid.PcdPerformanceEnable|TRUE" > /dev/null
      if [ "$?" -ne 0 ]; then
        echo "gPlatformModuleTokenSpaceGuid.PcdPerformanceEnable|TRUE" >> PlatformPkgExtConfig.dsc
      fi
    fi
  else
    cat "$WORKSPACE/$PLATFORM_PACKAGE/PlatformPkgConfig.dsc" | grep "gPlatformModuleTokenSpaceGuid.PcdPerformanceEnable|TRUE" > /dev/null
    if [ "$?" -eq 0 ]; then
      export BUILD=P
    else
      cat "$WORKSPACE/$PLATFORM_PACKAGE/PlatformPkgExtConfig.dsc" | grep "gPlatformModuleTokenSpaceGuid.PcdPerformanceEnable|TRUE" > /dev/null
      if [ "$?" -eq 0 ]; then
        export BUILD=P
      fi
    fi
  fi
  export TEST_MENU_ENABLE=N
  cat "$WORKSPACE/$PLATFORM_PACKAGE/PlatformPkgConfig.dsc" | grep "gPlatformModuleTokenSpaceGuid.PcdTestMenuEnable|TRUE" > /dev/null
  if [ "$?" -eq 0 ]; then
    export TEST_MENU_ENABLE=Y
  else
    cat "$WORKSPACE/$PLATFORM_PACKAGE/PlatformPkgExtConfig.dsc" | grep "gPlatformModuleTokenSpaceGuid.PcdTestMenuEnable|TRUE" > /dev/null
    if [ "$?" -eq 0 ]; then
      export TEST_MENU_ENABLE=Y
    fi
  fi

  #
  # Setup BIOS_SIZE_OPTION if it isn't predefined
  #
  if [ -z "$BIOS_SIZE_OPTION" ]; then
    export BIOS_SIZE_OPTION=-DBIOS_SIZE_OPTION=SIZE_70
  fi
  export EXT_BUILD_FLAGS="$EXT_BUILD_FLAGS $BIOS_SIZE_OPTION"
  echo
  echo "printing the build type ([U]nified, [N]on-Restricted, [I]nternal, [P]erformance, [S]V, SL[E])"
  echo "Build type ($BUILD)"
  echo
  
  #
  # Check for Embedded build flag
  #
  export EMBEDDED_BUILD=FALSE
  cat "$WORKSPACE/$PLATFORM_PACKAGE/PlatformPkgExtConfig.dsc" | grep "gPlatformModuleTokenSpaceGuid.PcdEmbeddedEnable|TRUE" > /dev/null
  if [ "$?" -eq 0 ]; then
    export EMBEDDED_BUILD=TRUE
    export BIOS_ID_FILE=$BUILD_DIR/BiosIdEmb.env
  fi
fi

cd $PLATFORM_PACKAGE

if [ -n "$WORKSPACE_ADDITIONAL_TOOLS_PATH" ]; then
        export WORKSPACE_ADDITIONAL_TOOLS_PATH=$WORKSPACE/$CLIENT_COMMON_PACKAGE/Override/BpCommonPkg/Tools/FCE:$WORKSPACE/$CLIENT_COMMON_PACKAGE/Override/BpCommonPkg/Tools/FMMT:$WORKSPACE/$BP_COMMON_PACKAGE/Restricted/Tools/KeyEnroll:$WORKSPACE/$CLIENT_COMMON_PACKAGE/Tools/SignFv:$WORKSPACE/$PLATFORM_PACKAGE/Tools/ToolScripts/SignFv
        export PATH=$WORKSPACE_ADDITIONAL_TOOLS_PATH:$PATH
fi
export EFI_SOURCE=$WORKSPACE/

if [ "$SILENT_MODE" = "TRUE" ]; then
  echo "************************************************************************" > Prep.log
  echo "***********           PreBuild.sh is launched here          ***********" >> Prep.log
  echo "************************************************************************" >> Prep.log
  ./PreBuild.sh $PrepRelease $CapsuleBuild 1>>Prep.log 2>&1
else
  ./PreBuild.sh $PrepRelease $CapsuleBuild
fi

if [ $? -ne 0 ]; then
  echo
  echo "!! The EDKII BIOS build has failed in PreBuild.sh!"
  echo
  exit 1
fi

#
# Run the primary build phase
#
./PriBuild.sh
ret=$?
if [ $ret -ne 0 ]; then
  exit $ret
fi
